<?php
define('TS_ROOT', './');
require(TS_ROOT .'common.php');
require(INC_DIR . 'bbcode.php');

$max_blog_title = 200;
$max_blog_massege = 500;

if ($ts_cfg['blog_enabled'])
{
	$datastore->enqueue('blog_show');
}

// Start session management
$user->session_start();

$sql = "
		SELECT SQL_CACHE
			* FROM ". TS_BLOGS ." WHERE show_blog_of_index = 1 ORDER BY blog_time
";
$cache = 'index_sql_' . md5($sql);

if ($ts_cfg['blog_enabled'])
{
	if (!$blog_body = CACHE('ts_cache')->get($cache))
	{
		$blog_body = array();
		foreach(DB()->fetch_rowset($sql) as $row_blog_news)
		{
			$template->assign_block_vars('index', array(
				'BLOGS_ID'     => $row_blog_news['blog_id'],
				'BLOG_TITLE'   => wbr(str_short($row_blog_news['blog_title'], $max_blog_title)),
				'BLOG_LINK'	   => BLOG_URL . $row_blog_news['blog_id'],
				'BLOG_TEXT'	   => wbr(str_short(bbcode2html($row_blog_news['blog_text']), $max_blog_massege)),
				'BLOG_POSTER'  => $row_blog_news['blog_poster'],
				'BLOG_TIME'	   => bb_date($row_blog_news['blog_time']),
			));
		}
		CACHE('ts_cache')->set($cache, $blog_body, 180);	
	}
}

// Show blog index
if ($ts_cfg['blog_enabled'])
{
	if (!$blog_show = $datastore->get('blog_show'))
	{
		$datastore->update('blog_show');
		$blog_show = $datastore->get('blog_show');
	}
	
	$template->assign_vars(array(
		'SHOW_BLOG_NEWS' => true,
	));
	
	foreach($blog_show as $show)
	{
		$template->assign_block_vars('show', array(
			'SHOW_BLOG_ID' 		=> $show['blog_id'],
			'SHOW_LINK'			=> BLOG_URL . $show['blog_id'],
			'SHOW_TITLE'    	=> str_short($show['blog_title'], $ts_cfg['max_show_blog_title']),
			'PRE_TITLE'			=> $show['blog_title'],
			'SHOW_TIME'     	=> $show['blog_time'],
		));
	}
}

// Allow cron
if (IS_AM)
{
	if (file_exists(CRON_RUNNING))
	{
		if (file_exists(CRON_ALLOWED))
		{
			unlink (CRON_ALLOWED);
		}
		rename(CRON_RUNNING, CRON_ALLOWED);
	}
}

print_page('index.tmpl');